import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/login_textfield.dart';
import 'package:find_friend/root/root_page.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:page_transition/page_transition.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginModUserNamePage extends StatefulWidget {
  @override
  _LoginModUserNamePageState createState() => _LoginModUserNamePageState();
}

class _LoginModUserNamePageState extends State<LoginModUserNamePage> {

  final TextEditingController _nameController = TextEditingController();
  final FocusNode _nameFocus = FocusNode();
  final _scaffoldKey = GlobalKey<ScaffoldState>();

  File _fileImage;
  bool isupload = false;
  List<String> randomNames = [];

  @override
  void initState() {
    super.initState();

    _requestName();
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }
  
  _chooseImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _fileImage = image;
    });
    isupload = true;
  }

  _requestName() {
    Networktool.request(API.randominfo,method: NETWORKHTTPMethod.GET, success: (data){
      if(data["data"] != null) {
        List arr = data["data"]["name"];
        arr.forEach((element) { 
          randomNames.add(element.toString());
        });
      }
    });
  }

  _upload() {
    if(_nameController.text == "") {
      AlertTool.showToast("请输入昵称");
      return;
    }
    if(!isupload) {
      AlertTool.showToast("请选择头像");
      return;
    }
    Networktool.uploadImage(API.edit, _fileImage, (data) async {
      print("$data");
      if(data["data"] != null) {
        SharedPreferences share = await SharedPreferences.getInstance();
        String tempJS = json.encode(data["data"]);
        share.setString(KEY_userjosn_info, tempJS);
        _jumpToRoot();
      }
    }, params: {"nickname":_nameController.text},
    fail: (msg) => AlertTool.showToast(msg));
  }

  _jumpToRoot() {
    Navigator.of(_scaffoldKey.currentContext).pushAndRemoveUntil(
      PageTransition(
        type: PageTransitionType.fade,
        child: RootPage()
      ),
      (route) => false
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      body: SafeArea(
        key: _scaffoldKey,
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: (){
            _nameFocus.unfocus();
          },
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              IconButton(
                icon: Image.asset("assets/zhuce-fanhui.png"),
                onPressed: () => Navigator.of(context).pop()
              ),
              Padding(
                padding: const EdgeInsets.only(top: 87, left: 40, right: 40),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("头像&昵称", style: TextStyle(
                        fontSize: 22,
                        fontWeight: FontWeight.bold
                    )),
                    Container(
                      alignment: Alignment.center,
                      child: FlatButton(
                        onPressed: _chooseImage,
                        child: Column(
                          children: [
                            _fileImage == null ? Image.asset("assets/zhuce-touxiang.png") : Image.file(_fileImage,width: 75,height: 75,),
                            SizedBox(height: 4.5,),
                            Text("点击设置头像")
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 48,),
                    Text("取个有个性的昵称吧～", style: TextStyle(fontSize: 11, color: APP_font_grey)),
                    Padding(
                      padding: const EdgeInsets.only(top:25),
                      child: Row(
                          children: [
                            Expanded(
                              child: LoginTextField(
                                focusNode: _nameFocus,
                                controller: _nameController,
                                maxlength: 10,
                                placeholder: "请输入昵称（十字以内）",
                              ),
                            ),
                            IconButton(
                              icon: Image.asset("assets/zhuce-suiji.png"),
                              onPressed: () => _nameController.text = randomNames[Random().nextInt(randomNames.length)],
                            )
                          ],
                        ),
                    ),
                  ],
                ),
              ),
              Spacer(),
              Center(
                child: FlatButton(
                  onPressed: _upload,
                  child: Padding(
                    padding: const EdgeInsets.only(bottom: 30),
                    child: Column(
                      children: [
                        Image.asset("assets/zhuce-xia.png"),
                        SizedBox(height: 20,),
                        Text("进入找他", style: instanceTextStyle(14, APP_font_black),)
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}